﻿namespace Hidistro.UI.Web.API
{
    using Hidistro.Membership.Context;
    using Hishop.Weixin.MP.Util;
    using System;
    using System.IO;
    using System.Web;

    public class wx : IHttpHandler
    {
        Log WxRunLog = new Log("/Log/");
        Log WxErrorLog = new Log("/Log/error/");
        public void ProcessRequest(HttpContext context)
        {
            try
            {
                HttpRequest request = context.Request;
                string weixinToken = SettingsManager.GetMasterSettings(false).WeixinToken;
                string signature = request["signature"];
                string nonce = request["nonce"];
                string timestamp = request["timestamp"];
                string s = request["echostr"];
                WxRunLog.addLine("weixinToken: " + weixinToken);
                WxRunLog.addLine("signature: " + signature);
                WxRunLog.addLine("nonce: " + nonce);
                WxRunLog.addLine("timestamp: " + timestamp);
                WxRunLog.addLine("s: " + s);
                WxRunLog.logSave();
                if (request.HttpMethod == "GET")
                {
                    if (CheckSignature.Check(signature, timestamp, nonce, weixinToken))
                    {
                        context.Response.Write(s);
                    }
                    else
                    {
                        context.Response.Write("");
                    }
                    context.Response.End();
                }
                else
                {
                    CustomMsgHandler handler = new CustomMsgHandler(request.InputStream);
                    handler.Execute();
                    WxRunLog.addLine("CreateTime: " + handler.RequestMessage.CreateTime.ToString());
                    WxRunLog.addLine("FromUserName: " + handler.RequestMessage.FromUserName);
                    WxRunLog.addLine("MsgId: " + handler.RequestMessage.MsgId);
                    WxRunLog.addLine("MsgType: " + handler.RequestMessage.MsgType);
                    WxRunLog.addLine("ToUserName: " + handler.RequestMessage.ToUserName);
                    WxRunLog.logSave();
                    context.Response.Write(handler.ResponseDocument);
                }
            }
            catch (Exception e)
            {
                WxErrorLog.addLine("Message: " + e.Message);
                WxErrorLog.logSave();
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

